from flask import Blueprint, render_template, request, session, flash, redirect, url_for, session, jsonify
import uuid
from ..database.User import User
from ..database import db

index_bp = Blueprint('index_bp', __name__)


@index_bp.route('/')
def index():
    username = session.get('username')
    if username:
        return f'hello, {username}'
    else:
        return '请登录'


@index_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.json.get('username')
        password = request.json.get('password')
        print('登录请求:', username, password)

        user = User.query.filter_by(username=username).first()
        if user:
            if user.password == password:
                session['username'] = username
                return jsonify({'status': 200, 'msg': '登录成功'})   # todo:后续安全加固
            else:
                return jsonify({'status': 401, 'error': 'Unauthorized', 'message': 'Incorrect password'})
        else:
            return jsonify({'status': 401})
    else:
        return 'fail'

# TODO: 此处需要后期优化

@index_bp.route('/authenticate', methods=['GET'])
def authenticate():
    username = session.get('username')
    if username:
        print(username)
        return jsonify({'status': 200})
    else:
        return jsonify({'status': 401})
    


@index_bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    elif request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        email = request.form.get('email')

        # 检查用户名和邮箱是否已经存在
        # existing_user = User.query.filter((User.username == username) | (User.email == email)).first()
        # if existing_user:
        #     flash("用户名或邮箱已存在，请尝试其他用户名或邮箱", "error")
        #     return redirect(url_for('index_bp.register'))

        # 创建新用户
        new_user = User(username=username, password=password, email=email)
        db.session.add(new_user)
        db.session.commit()

        return redirect(url_for('index_bp.login'))
    else:
        return "fail"



